<?php

namespace App\Controllers\v1;

use App\Models\SafeCenter;
use App\Models\UserLog;
use App\Models\UserProperty;
use App\Services\UserLogService;
use App\Services\UserPropertyService;
use common\utils\RSACrypt;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use common\utils\SysCode;
use App\Controllers\BaseController;
use App\Services\SettingService;
use App\Services\UserService;
use App\Services\AuthService;
use App\Services\SafeCenterService;
use App\User;

class UserController extends BaseController
{
    public $allows = ['login', 'register', 'getRegister', 'needVcode', 'vcode', 'postEmail', 'postMobile', 'getResetPwd', 'validEmail', 'validMobile', 'patchPassword'];

    public function getAccount(Request $request)
    {
        $user = Auth::user();
        return UserService::getWallet($user->id, $user->username);
    }

    //忘记密码（检验重置密码的用户名/手机/邮箱）
    public function getResetPwd(Request $request)
    {
        $params = $this->validate($request, [
            'data' => 'required'
        ]);
        return UserService::forgetPwd($params['data']);
    }

    public function needVcode(Request $request)
    {
        return ['required' => SettingService::getVCodeSwitch()];
    }

    /**
     * 获取手机号码
     */
    public function getMobile(Request $request)
    {
        $re = null;
        $id = Auth::user()['id'];
        $result = UserService::getBaseinfo($id);
        if (!empty($result['mobile'])) {
            $re = UserService::hideInfo('mobile', $result['mobile']);
        }
        return $re;
    }

    /**
     * 验证手机号码
     */
    public function validMobile(Request $request)
    {
        $params = $this->validate($request, [
            'code' => 'required'
        ]);
        $id = UserService::getUserId($request->all());
        $baseInfo = UserService::getBaseinfo($id);
        if (empty($baseInfo['mobile'])) {
            error_exit(SysCode::INVALID_ARGUMENT);
        }
        if (SafeCenterService::validateMobileCode($id, $baseInfo['mobile'], $params['code'])) {
            return SafeCenterService::setUniqueCode($id);
        } else {
            return "false";
        }
    }

    /**
     * 修改手机号码
     */
    public function patchMobile(Request $request)
    {
        $params = $this->validate($request, [
            'mobile' => 'required',
            'code' => 'required',
            'check' => 'required'
        ]);
        $id = Auth::user()['id'];
        if (UserService::updateMobile($id, $params['mobile'], $params['code'], $params['check'])) {
            return "true";
        } else {
            return "false";
        }
    }

    /**
     * 设置手机号码
     */
    public function putMobile(Request $request)
    {
        $params = $this->validate($request, [
            'mobile' => 'required',
            'code' => 'required'
        ]);
        $id = Auth::user()['id'];
        if (UserService::setMobile($id, $params['mobile'], $params['code'])) {
            return "true";
        } else {
            return "false";
        }
    }


    /**
     * 验证谷歌身份
     */
    public function postGoogleAuth(Request $request)
    {
        $params = $this->validate($request, [
            'secret' => 'required',
            'code' => 'required'
        ]);
        $id = Auth::user()['id'];
        if (UserService::googleAuth($params['secret'], $params['code'], $id)) {
            $code = SafeCenterService::setUniqueCode($id);
            return $code;
        }
    }

    /**
     * 获取谷歌验证数据
     */
    public function getGoogleAuth(Request $request)
    {
        //获取谷歌密钥及二维码
        $params = $request->all();
        $data['width'] = isset($params['width']) ? $params['width'] : 300;
        $data['height'] = isset($params['height']) ? $params['height'] : 300;
        $title = isset($params['title']) ? $params['title'] : "澳金国际";
        $resutl = AuthService::getGoogleAuth($title, $data);
        return $resutl;
    }

    /**
     * 获取邮箱
     */
    public function getEmail(Request $request)
    {
        $email = null;
        $id = Auth::user()['id'];
        $result = UserService::getBaseinfo($id);
        if (!empty($result['email'])) {
            $email = UserService::hideInfo('email', $result['email']);
        }
        return $email;
    }

    /**
     * 验证邮箱验证码
     */
    public function validEmail(Request $request)
    {
        $params = $this->validate($request, [
            'code' => 'required'
        ]);
        $id = UserService::getUserId($request->all());
        $baseInfo = UserService::getBaseinfo($id);
        if (empty($baseInfo['email'])) {
            error_exit(SysCode::INVALID_ARGUMENT);
        }
        if (SafeCenterService::validateEmailCode($id, $baseInfo['email'], $params['code'])) {
            return SafeCenterService::setUniqueCode($id);
        } else {
            return "false";
        }
    }

    /**
     * 修改邮箱
     */
    public function patchEmail(Request $request)
    {
        $params = $this->validate($request, [
            'email' => 'required',
            'code' => 'required',
            'check' => 'required'
        ]);
        $id = Auth::user()['id'];
        if (UserService::updateEmail($id, $params['email'], $params['code'], $params['check'])) {
            return "true";
        } else {
            return "false";
        }
    }

    /**
     * 设置邮箱
     */
    public function putEmail(Request $request)
    {
        $params = $this->validate($request, [
            'email' => 'required',
            'code' => 'required'
        ]);
        $id = Auth::user()['id'];
        if (UserService::setEmail($id, $params['email'], $params['code'])) {
            return "true";
        } else {
            return "false";
        }
    }

    /**
     * 发送邮箱验证码
     */
    public function postEmail(Request $request)
    {
        $id = UserService::getUserId($request->all());
        if (!$email = $request->get('email')) {
            $userInfo = UserService::getBaseinfo($id);
            if (empty($userInfo['email'])) {
                error_exit(SysCode::INVALID_ARGUMENT);
            } else {
                $email = $userInfo['email'];
            }
        }
        if (SafeCenterService::sendEmailCode($id, $email)) {
            return "true";
        }
        error_exit(SysCode::FAILED);
    }

    /**
     * 发送手机验证码
     */
    public function postMobile(Request $request)
    {
        $id = UserService::getUserId($request->all());
        if (!$mobile = $request->get('mobile')) {
            $userInfo = UserService::getBaseinfo($id);
            if (empty($userInfo['mobile'])) {
                error_exit(SysCode::INVALID_ARGUMENT);
            } else {
                $mobile = $userInfo['mobile'];
            }
        }
        $re = SafeCenterService::sendMobileCode($id, $mobile);
        if ($re === true) {
            return "true";
        }else{
            error_exit(SysCode::USER_MOBILE_SENDERROR, $re);
        }
    }

    /**
     * 修改提款密码
     */
    public function patchWithdrawPwd(Request $request)
    {
        $params = $this->validate($request, [
            'old_pwd' => 'required',
            'new_pwd' => 'required'
        ]);
        $user = Auth::user()->toArray();
        if (UserService::modifyWithdrawPassword($user['id'], array_merge($params, $user))) {
            return "true";
        }
        error_exit(SysCode::FAILED);
    }

    /**
     * 设置提款密码
     */
    public function putWithdrawPwd(Request $request)
    {
        $params = $this->validate($request, [
            'pwd' => 'required',
            "check" => 'required'
        ]);
        $id = Auth::user()['id'];
        if (UserService::setWithdrawPassword($id, $params)) {
            return __('message.save_login_password');
        }
        error_exit(SysCode::FAILED);
    }

    /**
     * 修改登陆密码
     * */
    public function patchPassword(Request $request)
    {
        $params = $request->all();
        if (!isset($params['old_pwd']) && !isset($params['check'])) {
            error_exit(SysCode::INVALID_ARGUMENT);
        }
        $user = Auth::user();
        if ($user) {
            $id = $user['id'];
        } else {
            $id = $request->input("id");
            if (!isset($id) || empty($id)) {
                error_exit(SysCode::INVALID_ARGUMENT);
            }
        }
        if (UserService::modifyPassword($id, $params)) {
            return __('message.save_login_password');
        }
        return error_exit(SysCode::USER_PASSWORD_ERROR);
    }

    /**
     * 验证登陆密码
     * */
    public function validPassword(Request $request)
    {
        $data = $this->validate($request, [
            'pwd' => 'required'
        ]);
        $id = Auth::user()['id'];
        if (UserService::verifyPassword($data['pwd'], $id)) {
            $code = SafeCenterService::setUniqueCode($id);
            return $code;
        }
        return error_exit(SysCode::USER_PASSWORD_ERROR);
    }

    /**
     * 实名认证（真是姓名、身份证号）
     * */
    public function getRealname(Request $request)
    {
        $user = Auth::user();
        return UserService::getRealname($user->id);
    }

    /**
     * 获取身份证
     * */
    public function getIdcard(Request $request)
    {
        $user = Auth::user();
        $re = UserService::getIdcard($user->id);
        return $re;
    }

    /**
     * 安全信息
     * */
    public function safetyInfo(Request $request)
    {
        $user = Auth::user();
        $re = UserService::getSafetyInfo($user->id);
        return $re;
    }


    public function login(Request $request)
    {
        // 是否需要验证码
        if (SettingService::getVCodeSwitch()) {
            $code = $request->input('vcode', false);
            $hash = $request->input('hash', false);

            if (!$code || !$hash) {
                return error_exit(SysCode::INVALID_CODE);
            }

            if (!UserService::validateVcode($hash, $code)) {
                return error_exit(SysCode::INVALID_CODE);
            }
        }

        $credentials = $request->only(['username', 'agent', 'demo', 'password']);

        $ret = UserService::login($credentials);

        return $ret;
    }

    public function loginByCode(Request $request)
    {
        $this->validate($request, [
            'code' => 'required',
        ]);
        $credentials = $request->only(['email', 'mobile']);
        $code = $request->input('code');

        $ret = UserService::loginByCode($credentials, $code);

        return $ret;
    }

    public function register(Request $request)
    {
        $require = SettingService::getRegisterItems();
        $rule = [
            'username' => 'required',
            'password' => 'required'
        ];
        $attrs = [
            'username' => $request->input('username'),
            'password' => $request->input('password'),
        ];
        foreach ($require as $r) {
            if ($r['required']) {
                $rule[$r['name']] = 'required';
            }
            if ($request->has($r['name'])) {
                $attrs[$r['name']] = $request->input($r['name']);
            }
        }

        $this->validate($request, $rule);

        if (UserService::register($attrs)) {
            $credentials = $request->only('username', 'password');
            return UserService::login($credentials);
        }
        return error_exit(SysCode::INTERNAL_SERVER_ERROR);
    }

    public function getRegister()
    {
        return SettingService::getRegisterItems();
    }

    public function logout()
    {
        return UserService::logout();
    }

    public function vcode()
    {
        return UserService::getVcode();
    }
}
